package com.china08.yxyapi.api.manage.tec.teaching.lecture.pack;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack.Res;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePackRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePrePackRepository;
import com.china08.yxyapi.service.manage.tec.teaching.lecture.LectureCrtPackAndHomeworkService;
import com.china08.yxyapi.util.JpushForMessageUtil;
import com.china08.yxyapi.util.JpushForNotificationUtil;
import com.china08.yxyapi.util.YxUserPointsUtilV3;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---备授课--添加授课（发布备课包）</br>
 * Richard.Wang 增加资源发布时的用途, 根据用户,需要发布
 * 
 */
@CrossOrigin
@RestController
public class LectureCrtPackAndHomeworkController extends YxyApiBaseController {

    @Autowired
    private YxyLecturePrePackRepository yxyLecturePrePackRepository;

    @Autowired
    private LectureCrtPackAndHomeworkService lectureCrtPackAndHomeworkService;

    @Autowired
    private YxyLecturePackRepository yxyLecturePackRepository;

    @Autowired
    private YxUserPointsUtilV3 yxUserPointsUtilV3;

    @ApiOperation(value = "老师 ---备授课--添加授课（发布备课包）")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/pack/homework/crt", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req,
            RespModel respModel) throws ParseException {

        String userId = getProfile(request, response).getId();
        String userNick = getProfile(request, response).getUserNick();
        String schoolId = getProfile(request, response).getSchoolId();
        String schoolName = getProfile(request, response).getSchoolName();
        String domainName = getDomainName(request);

        // 判断资源用途 1 授课 2 预习作业 3 课后作业 4 测试
        Assert.notNull(StringUtils.defaultIfBlank(userId, null), "用户id必须");
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "学校id必须");
        yxUserPointsUtilV3.homeworkBackpack(userId);
        YxyLecturePrePack yxyLecturePrePack = yxyLecturePrePackRepository.findById(req.prePackId);
        List<String> parentsId = new ArrayList<String>();
        if (yxyLecturePrePack != null) {
            for (MyClass classes : req.myClass) {
                YxyLecturePack yxyLecturePack = new YxyLecturePack();
                // BeanUtils.copyProperties(yxyLecturePack,
                // yxyLecturePrePack);
                List<StuModel> studentModelList = classes.studentModelList;
                String phaseId = yxyLecturePrePack.getPhaseId();
                String phaseName = yxyLecturePrePack.getPhaseName();
                String versionId = yxyLecturePrePack.getVersionId();
                String versionName = yxyLecturePrePack.getVersionName();
                String semesterId = yxyLecturePrePack.getSemesterId();
                String semesterName = yxyLecturePrePack.getSemesterName();
                String bookContentId = yxyLecturePrePack.getBookcontentsId();
                String bookContentName = yxyLecturePrePack.getBookcontentsName();
                String packName = yxyLecturePrePack.getPackName();
                String subjectId = yxyLecturePrePack.getSubjectId();
                String subjectName = yxyLecturePrePack.getSubjectName();
                List<Res> res = yxyLecturePrePack.getResources();
                List<com.china08.yxyapi.entity.mg.lecture.YxyLecturePack.Res> packRes = new ArrayList<YxyLecturePack.Res>();
                for (Res res2 : res) {
                    Integer aInteger = 0;
                    Integer bInteger = 0;
                    Integer cInteger = 0;
                    Integer dInteger = 0;
                    List<RequesRes> resList1 = req.requesRes;
                    for (RequesRes requesRes : resList1) {
                        if (requesRes.resId.equals(res2.getResourceId())) {
                            List<Integer> resUsed = requesRes.resUsed;
                            for (Integer used : resUsed) {
                                if (5 != used) {
                                    if (1 == used) {
                                        aInteger = 1;
                                    }
                                    if (2 == used) {
                                        bInteger = 1;
                                    }
                                    if (3 == used) {
                                        cInteger = 1;
                                    }
                                    if (4 == used) {
                                        dInteger = 1;
                                    }
                                }
                            }
                        }
                    }
                    com.china08.yxyapi.entity.mg.lecture.YxyLecturePack.Res res3 = new com.china08.yxyapi.entity.mg.lecture.YxyLecturePack().new Res();
                    res3.setOrderNum(res2.getOrderNum());
                    res3.setCourseType(res2.getCourseType());
                    res3.setFormatId(res2.getFormatId());
                    res3.setResourceId(res2.getResourceId());
                    res3.setResourceName(res2.getResourceName());
                    res3.setFileSize(res2.getFileSize());
                    String url = "";
                    if (domainName.contains("hrbeduy")) {
                        url = "yxyres.hrbeduy.com/res/browse/";
                    } else {
                        url = "yxy.res.91yunxiao.com/res/browse/";
                    }
                    url = url + res2.getResourceId();
                    res3.setResourceUrl(url);
                    res3.setUsesHomework(cInteger);
                    res3.setUsesProview(bInteger);
                    res3.setUsesTeaching(aInteger);
                    res3.setUsesTest(dInteger);
                    packRes.add(res3);
                }
                yxyLecturePack.setSubjectId(subjectId);
                yxyLecturePack.setSubjectName(subjectName);
                yxyLecturePack.setPhaseId(phaseId);
                yxyLecturePack.setPhaseName(phaseName);
                yxyLecturePack.setPackName(packName);
                yxyLecturePack.setVersionId(versionId);
                yxyLecturePack.setVersionName(versionName);
                yxyLecturePack.setSemesterId(semesterId);
                yxyLecturePack.setSemesterName(semesterName);
                yxyLecturePack.setBookcontentsId(bookContentId);
                yxyLecturePack.setBookcontentsName(bookContentName);
                yxyLecturePack.setResources(packRes);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                req.preDate = req.preDate.replace("Z", " UTC");
                Date date = format.parse(req.preDate);
                yxyLecturePack.setPreDate(date);
                yxyLecturePack.setUserId(userId);
                yxyLecturePack.setUserNick(yxyLecturePrePack.getUserNick());
                yxyLecturePack.setSchoolNick(yxyLecturePrePack.getSchoolNick());
                yxyLecturePack.setPackSize(yxyLecturePrePack.getPackSize());
                yxyLecturePack.setSchoolId(schoolId);
                yxyLecturePack.setClassId(classes.classId);
                yxyLecturePack.setClassName(classes.classNick);
                yxyLecturePackRepository.save(yxyLecturePack);
                classes.packId = yxyLecturePack.getId();
                for (StuModel stuModel : studentModelList) {
                    parentsId.addAll(stuModel.parentsId);
                }
            }
        }
        List<String> parentsIdnew = new ArrayList<>();
        for (String string : parentsId) {
            if (!parentsIdnew.contains(string)) {
                parentsIdnew.add(string);
            }
        }
        lectureCrtPackAndHomeworkService.createHomework(req.prePackId, req.requesRes, req.usesProviewBeginDate,
                req.usesProviewEndDate, req.usesHomeworkBeginDate, req.usesHomeworkEndDate, req.myClass, schoolId,
                schoolName, userId, userNick, parentsIdnew, domainName);
        respModel = new RespModel();
        respModel.setMessage("备授课-成品备课包创建成功");
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {

        public String prePackId;

        public String preDate;

        // 发布作业需要前台将资源的用途传递过来,</br>
        // 根据资源用途,进行作业的发布.
        public List<RequesRes> requesRes;

        // 预习作业开始时间
        public String usesProviewBeginDate;
        // 预习作业结束时间
        public String usesProviewEndDate;

        // 课后作业开始时间
        public String usesHomeworkBeginDate;
        // 课后作业结束时间
        public String usesHomeworkEndDate;

        /**
         * 资源id
         */
        public List<MyClass> myClass;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(prePackId, null), "请选择授课目录");
            Assert.notNull(StringUtils.defaultIfBlank(preDate, null), "授课时间为必填项");
            Assert.notEmpty(myClass, "班级必须大于1个");
        }

    }

    // 极光推送
    public static void sendMessage(String subjectName, String schoolId, List<String> parentsIdnew, Date date) {

        // 当前时间延迟20秒
        Date pubDate = date;
        Date curDate = new Date();

        Calendar dateOne = Calendar.getInstance();
        dateOne.setTime(pubDate);

        Calendar dateTwo = Calendar.getInstance();
        dateTwo.setTime(curDate);

        long timeOne = dateOne.getTimeInMillis();
        long timeTwo = dateTwo.getTimeInMillis();
        long minute = (timeOne - timeTwo) / (1000 * 60);

        Date time = null;
        if (minute > 3) {
            time = date;
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.SECOND, 20);
            time = calendar.getTime();
        }

        List<String> tabAndList = new ArrayList<>();
        tabAndList.add("PARENTS" + schoolId);
        // message 推送消息
        List<Integer> roleIdList = new ArrayList<>();
        roleIdList.add(1);
        JpushForMessageUtil.sendMessageTiming(8, roleIdList, schoolId, parentsIdnew, tabAndList, time);

        // notification
        Map<String, String> map = new HashMap<String, String>();
        map.put("modelId", "homeworkNotice");
        String alert = "您的孩子有一份" + subjectName + "作业";
        JpushForNotificationUtil.sendNotificationTiming(alert, "班级作业", map, parentsIdnew, tabAndList, time);

        // 电子书包----定时推送作业
        JpushForNotificationUtil.sendNotificationPack(alert, "班级作业", map, parentsIdnew, null, time);
    }

    /**
     * @author Administrator
     *
     */
    public static class RequesRes {
        // 资源id
        public String resId;

        // 资源名称,题组名称
        public String resName;

        // 资源对应的url
        public String resUrl;

        // 0 试题 1资源
        public int courseType;

        // 资源用途
        public List<Integer> resUsed;
        // 增加资源用途 ---教学
        public Integer usesTeaching = 0;
        // 增加资源用途 ---预习作业
        public Integer usesProview = 0;

        // 增加资源用途 ---课后作业
        public Integer usesHomework = 0;
        // 增加资源用途 ---测试
        public Integer usesTest = 0;

    }

    public static class MyClass {
        // 授课包ID
        public String packId = "";
        // 班级id
        public String classId;
        // 班级名称
        public String classNick;
        // 年级
        public String grade;
        // 学生数量
        public Integer studentNum;
        // 班级里学生
        public List<StuModel> studentModelList;
    }

    public static class StuModel {

        // 学生id
        public String studentId;
        // 学生姓名
        public String studentName;
        // 学生头像
        public String avatar;
        // 学生家长
        public List<String> parentsId;

    }

    protected static class RespModel extends YxyApiRespModel {

    }
}
